package com.xzz.tree;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

/**
 * @author: hhz
 * @create: 2021-12-22 15:14
 * 341. 扁平化嵌套列表迭代器
 **/
public class NestedIterator implements Iterator<Integer> {
    Iterator<Integer> it;
    public NestedIterator(List<NestedInteger> nestedList) {
        List<Integer> list = new LinkedList<>();
        for (NestedInteger nestedInteger : nestedList) {
            traverse(nestedInteger,list);
        }
        it = list.iterator();
    }
    @Override
    public boolean hasNext() {
        return it.hasNext();
    }

    @Override
    public Integer next() {
        return it.next();
    }
    private void traverse(NestedInteger root, List<Integer> result) {
        if(root.isInteger()){
            result.add(root.getInteger());
        }else {
            List<NestedInteger> list = root.getList();
            for (NestedInteger nestedInteger : list) {
                traverse(nestedInteger,result);
            }
        }
    }
}
